import { _decorator, Animation, BoxCollider2D, Collider2D, Component, Contact2DType, EventTouch, IPhysics2DContact, Label, log, Node, PHYSICS_2D_PTM_RATIO, PhysicsSystem2D, RigidBody2D, tween, UITransform, v2 } from 'cc';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

// 游戏状态
enum BirdState{
    //准备状态
    Ready,
    //小鸟飞行中
    Flying,
    //小鸟自由落体中
    FreeFall,
    //小鸟已阵亡
    Dead,
};

@ccclass('Player')
export class Player extends Component {
    // 分数
    @property(Label)
    scoreLabel: Label = null;
    // 小鸟飞行动画
    @property(Animation)
    birdAnim: Animation = null;
    // 带重力和碰撞体的小鸟
    private _bird2D: Node = null;
    // 2D刚体
    private _rigidBody2D: RigidBody2D = null;
    // 2D碰撞体
    private _collider2D: BoxCollider2D = null;
    // 游戏状态
    private _state = BirdState.Ready;
    // 上抛的初始速度
    private _throwForce: number = 70;
    // 上抛缓动动画
    private _tweenAction

    // 游戏管理器
    private _gameManager: GameManager;
    // 下个未通过的水管
    private _nextPipe: Node;
    // 实时分数
    private _score: number = 0;

    /**
     * 初始化
     */
    start() {
        // 物理系统默认是开启的
        PhysicsSystem2D.instance.enable = true;
        // 默认的重力加速度是 10m/s，即(0,-10*PHYSICS_2D_PTM_RATIO），按照比率转换后(0, -320)世界单位/秒2
        PhysicsSystem2D.instance.gravity = v2(0, -20 * PHYSICS_2D_PTM_RATIO);
        this._bird2D = this.node.getChildByName("Bird2D");
        // 获取2D钢体
        this._rigidBody2D = this._bird2D.getComponent(RigidBody2D);
        // 获取2D碰撞体
        this._collider2D = this._bird2D.getComponent(BoxCollider2D);
        // 注册2D碰撞事件(碰撞开始时触发)
        this._collider2D.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        // 播放小鸟自身动画
        if (this.birdAnim) {
            this.birdAnim.play('birdFlapping');
            this.birdAnim.play('birdWing');
        }
    }

    /**
     * 开始游戏
     */
    public startTheGame(gameManager: GameManager) {
        // 游戏管理器
        this._gameManager = gameManager;
        // 获取下个未通过的水管
        this._nextPipe = this._gameManager.pipeLayer.getNextPipe();
        this._score = 0;
        // 停止小鸟上下浮动
        if (this.birdAnim) {
            this.birdAnim.stop();
            this.birdAnim.play('birdFlapping');
        }
        // 绑定触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.onTouchStart();
    }

    /**
     * 每一帧渲染前执行
     */
    update(deltaTime: number) {
        if (this._state === BirdState.Ready || this._state === BirdState.Dead) return;
        if (this._state === BirdState.Flying || this._state === BirdState.FreeFall) {
            // if (this._rigidBody2D.linearVelocity.y > 0) {
            //     log("小鸟起飞上升:", this._state, "，重力缩放比例:", this._rigidBody2D.gravityScale, "，重力加速度:", this._rigidBody2D.linearVelocity);
            // } else {
            //     this._state = BirdState.FreeFall;
            //     this._rigidBody2D.gravityScale += deltaTime;
            //     log("小鸟自由落体:", this._state, "，重力缩放比例:", this._rigidBody2D.gravityScale, "，重力加速度:", this._rigidBody2D.linearVelocity)
            // }
            // 记录得分
            let birdLeft = this._bird2D.getPosition().x;
            let pipeRight = this._nextPipe.getPosition().x + this._nextPipe.getComponent(UITransform).width;
            if (birdLeft > pipeRight) {
                // 得分 +1
                this._score++;
                this.scoreLabel.string = this._score.toString();
                // 获取下个未通过的水管
                this._nextPipe = this._gameManager.pipeLayer.getNextPipe();
            }
        }
    }

    /**
     * TOUCH事件回调 
     */
    onTouchStart() {
        // 重置 重力缩放比例（默认0无重力）
        this._rigidBody2D.gravityScale = 1;
        this._state = BirdState.Flying;
        // 上抛前清空重力加速度
        this._rigidBody2D.linearVelocity = v2();
        // 2D刚体上抛
        this._rigidBody2D.applyLinearImpulseToCenter(v2(0, this._throwForce), true);
        log("小鸟起飞:", this._state);
        // 上抛缓动动画
        if (this._tweenAction) {
            this._tweenAction.stop();
            this._tweenAction = null;
        };
        // 小鸟头朝右上
        this._tweenAction = tween(this._bird2D).to(.1, {angle: 30}, {easing: 'elasticOut'}).start();
        this.scheduleOnce(()=>{
            if (this._state != BirdState.Dead && this._tweenAction) {
                this._tweenAction.stop();
                // 小鸟头回正
                this._tweenAction = tween(this._bird2D).to(.1, {angle: 0}, {easing: 'cubicInOut'}).start();
            }
        }, .5);
    }

    /**
     * 碰撞检测 
     */
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 碰撞情况
        log("self:", selfCollider.node.name, "other:", otherCollider.node.name, "contact:", contact)
        // 碰撞后小鸟死亡
        this._state = BirdState.Dead;
        log("小鸟已阵亡:", this._state);
        // 停止飞行动画
        if (this.birdAnim) {
            this.birdAnim.stop();
        }
        // 缓动动画 小鸟头朝下
        if (this._tweenAction) {
            this._tweenAction.stop();
            this._tweenAction = tween(this._bird2D).to(.1, {angle: -90}, {easing: 'cubicInOut'}).start();
        };
        // 解除触摸事件绑定
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        // 发送自定义事件，传递 游戏结束
        this.node.emit('GameEnd', this._score);
    }

    onDestroy() {
        // 解除全局碰撞
        if (PhysicsSystem2D.instance) {
            PhysicsSystem2D.instance.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
}
